<?php

namespace app\admin\controller\paotui;

use app\admin\model\paotui\PostDispatch;
use app\admin\model\paotui\PostOrder;
use app\admin\model\paotui\PostSocket;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use Yansongda\Pay\Pay;

/**
 * 快递管理
 *
 * @icon fa fa-circle-o
 */
class Post extends Backend
{
    protected $type = ['1' => '支付', '2' => '抢单成功', '3' => '取件', '4' => '送达'];
    /**
     * Post模型对象
     * @var \app\admin\model\paotui\Post
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\paotui\Post;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter    = $this->request->get('filter', '');
            $filter    = json_decode($filter);
            $poster_id = empty($filter->poster_id) ? 0 : $filter->poster_id;
            unset($filter->poster_id);
            $this->request->get(['filter' => json_encode($filter)]);

            $type = $this->request->param('type', 1);
            switch ($type) {
                case 1:
                    $_where = ['pay_status' => 1, 'type' => ['in', '1,2']];
                    break;
                case 2:
                    $_where = ['pay_status' => 1, 'type' => 3];
                    break;
            }

            $_where1 = [];
            if ($poster_id) {
                $_where1 = function ($query) use ($poster_id) {
                    return $query->where("collect_poster_id", $poster_id)
                        ->whereOr('reach_poster_id', $poster_id);
                };
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($_where)
                ->where($_where1)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($_where)
                ->where($_where1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            foreach ($list as $k => &$v) {
                if ($v['poster_id']) {
                    $posterModel = new \app\admin\model\paotui\Poster();
                    $posterInfo  = $posterModel->where(['id' => $v['poster_id']])->find();
                    if (!empty($posterInfo)) {
                        $v['poster_name'] = $posterInfo['poster_name'] . "【" . $posterInfo['mobile'] . "】";
                    }
                } else {
                    $v['poster_name'] = "";
                }

                if ($poster_id) {
                    if ($v['collect_poster_id'] != $v['reach_poster_id']) {
                        $brokerage      = [$v['collect_poster_id'] => $v['collect_brokerage'], $v['reach_poster_id'] => $v['reach_brokerage']];
                        $v['brokerage'] = $brokerage[$poster_id];

                        if ($v['collect_poster_id'] == $poster_id) {
                            $poster_type = "揽收";
                        } else if ($v['reach_poster_id'] == $poster_id) {
                            $poster_type = "派送";
                        }

                        $v['poster_type'] = $poster_type;
                    } else {
                        $v['poster_type'] = "独立";
                    }
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 物流跟踪
     */
    public function order()
    {
        $ids = $this->request->param('ids');

        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            $id    = $this->request->param('id');
            $model = new PostOrder();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $model
                ->where($where)
                ->where("post_id", $id)
                ->order($sort, $order)
                ->count();

            $list = $model
                ->where($where)
                ->where("post_id", $id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $k => $v) {
                $list[$k]['type_name']  = $this->type[$v['type']];
                $list[$k]['createtime'] = date("Y-m-d H:i:s", $v['createtime']);
            }

            $list   = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $this->assign('id', $ids);
        return $this->view->fetch();
    }


    /**
     * 更换骑手
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function change_poster($ids = null)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if (!in_array($row['status'], [3, 4, 5])) {
                        $this->error("当前订单的状态已不能指派");
                    }
                    if ($row['status'] == 3) {
                        $params['collect_poster_id'] = $params['poster_id'];
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $posterModel = new \app\admin\model\paotui\Poster();
        $this->assign('poster', $posterModel->where(['status' => 1])->select());

        return $this->view->fetch();
    }

    /**
     * 手动指派
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hand_dispatch($ids = null)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if (!in_array($row['status'], [2, 8, 9])) {
                        $this->error("当前订单的状态已不能指派");
                    }

                    $postDispatchModel = new PostDispatch();
                    $postDispatchModel->save(['post_id' => $row['id'], 'poster_id' => $params['poster_id'], 'type' => 2]);

                    //生成socket记录
                    $postSocketModel = new PostSocket();
                    $postSocketInfo  = $postSocketModel->where(['post_id' => $row['id']])->find();
                    if ($postSocketInfo) {
                        $postSocketInfo->save(['type' => 3, 'poster_id' => $params['poster_id'], 'distance' => 0, 'send_num' => 0, 'next_send_time' => time(), 'send_status' => 0]);
                    } else {
                        $postSocketModel = new PostSocket();
                        $postSocketModel->save(['type' => 3, 'post_id' => $row['id'], 'poster_id' => $params['poster_id'], 'distance' => 0, 'send_num' => 0, 'next_send_time' => time(), 'send_status' => 0]);
                    }

                    $params['status'] = 8;
                    $result           = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $posterModel = new \app\admin\model\paotui\Poster();
        $this->assign('poster', $posterModel->where(['status' => 1])->select());

        return $this->view->fetch();
    }

}
